package HttpClient知识点;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ApacheHttpPostDemo {
    public static void main(String[] args) throws Exception {
        // 1. 创建 HttpClient 实例
        CloseableHttpClient client = HttpClients.createDefault();

        // 2. 创建 HttpPost 请求对象，设置 URL
        HttpPost post = new HttpPost("https://jsonplaceholder.typicode.com/posts");

        // 3. 构造请求体 JSON 字符串
        String json = "{"
                + "\"title\": \"foo\","
                + "\"body\": \"bar\","
                + "\"userId\": 1"
                + "}";

        // 4. 设置请求头和请求体
        post.setHeader("Content-Type", "application/json");
        post.setEntity(new StringEntity(json, "UTF-8"));

        // 5. 执行请求
        HttpResponse response = client.execute(post);

        // 6. 获取状态码和响应体
        int statusCode = response.getStatusLine().getStatusCode();
        String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");

        System.out.println("状态码: " + statusCode);
        System.out.println("响应内容: \n" + responseBody);

        // 7. 关闭客户端连接
        client.close();
    }
}

